import {
	onMounted,
	ref
} from 'vue'

import {
	QQMapWX
} from '@/sdk/new_file.js'



export function searchAddress() {
	const test = ref('testtttttttt')
	let qqmapsdk = null


	//搜索地址 
	function searchAddr(keyWord, location) {
		return new Promise((resolve, reject) => {
			qqmapsdk.search({
				keyword: keyWord, //搜索关键词
				location: location, //设置周边搜索中心点
				success: function(res) { //搜索成功后的回调
					var mks = []
					for (var i = 0; i < res.data.length; i++) {
						mks.push({ // 获取返回结果，放到mks数组中
							title: res.data[i].title,
							id: res.data[i].id,
							latitude: res.data[i].location.lat,
							longitude: res.data[i].location.lng,
							iconPath: "/resources/my_marker.png", //图标路径
							width: 20,
							height: 20
						})
					}
					resolve(mks)
				},
				fail: function(res) {
					console.log(res);
					reject()
				},
				complete: function(res) {
					console.log(res);
					reject()
				}
			})
		})
	}

	//获取城市列表
	function getCityList() {
		qqmapsdk.getCityList({
			success: function(res) { //成功后的回调
				// console.log(res);
				// console.log('省份数据：', res.result[0]); //打印省份数据
				// console.log('城市数据：', res.result[1]); //打印城市数据
				// console.log('区县数据：', res.result[2]); //打印区县数据
			},
			fail: function(error) {
				console.error(error);
			},
			complete: function(res) {
				console.log(res);
			}
		})
	}


	 
	/**
	 * 导航路径计算： 
	 * @param {Object} to 目标地址坐标
	 * @param {Array} waypoints 途径地点
	 */
	let navFun = (to, waypoints = null) => {
		return new Promise((resolve, reject) => {

			let pram = {
				mode: waypoints ? 'driving' : 'bicycling',
				to: {
					latitude: to.latitude,
					longitude: to.longitude
				},
				success: (res) => {
					//console.log(res);
					var ret = res;
					var coors = ret.result.routes[0].polyline,
						pl = [];
					//坐标解压（返回的点串坐标，通过前向差分进行压缩）
					var kr = 1000000;
					for (var i = 2; i < coors.length; i++) {
						coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
					}
					//将解压后的坐标放入点串数组pl中
					for (var i = 0; i < coors.length; i += 2) {
						pl.push({
							latitude: coors[i],
							longitude: coors[i + 1]  
						})
					}

					resolve({
						pl,
						ret: ret.result.routes[0]
					})

				},
				fail: (error) => {
					console.error(error);
					reject()
				},
				complete: (res) => {
					console.log(res);
					reject()
				}
			}
			if (waypoints)
				pram.waypoints = waypoints
			qqmapsdk.direction(pram)
		})
	}

	//初始化mapsdk
	let initMapSdk = () => {
		if (!qqmapsdk)
			qqmapsdk = new QQMapWX({
				key: 'JYEBZ-YCXCN-3RAFY-STD7N-4TNSS-SLFEX'
			});
		return qqmapsdk
	}
	onMounted(() => {
		initMapSdk()
	})

	return {
		searchAddr,
		navFun,
		getCityList,
		qqmapsdk,
		initMapSdk,
		test
	}
}